package cts.com.jaxb;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class TestTransactionXMLGeneration {

  private static final String NEFT_TRANSACTION_XML = "xml/neft.xml";

  public static void main(String[] args) throws JAXBException, IOException {

    ArrayList<TransactionBean> bookList = new ArrayList<TransactionBean>();

    // create books
    TransactionBean tBean1 = new TransactionBean();
    tBean1.setTransId("T1234");
    tBean1.setAmount(3000);
    tBean1.setDate("14-May-2013");
    tBean1.setTime("00:40:34");
    tBean1.setDescription("3k to HDFC");
    tBean1.setFromAccountNo("12345");
    tBean1.setToAccountNo("54321");
    tBean1.setFromIFSC("SBI1001");
    tBean1.setToIFSC("HDFC1224");
    bookList.add(tBean1);

    TransactionBean tBean2 = new TransactionBean();
    tBean2.setTransId("T1235");
    tBean2.setAmount(5000);
    tBean2.setDate("13-May-2014");
    tBean2.setTime("1:45:09");
    tBean2.setDescription("5k to ICICI");
    tBean2.setFromAccountNo("12346");
    tBean2.setToAccountNo("90890");
    tBean2.setFromIFSC("AC1001");
    tBean2.setToIFSC("HDFC1224");
    bookList.add(tBean2);

    // create bookstore, assigning book
    NEFTTransactions bookstore = new NEFTTransactions();
    bookstore.setBookList(bookList);

    // create JAXB context and instantiate marshaller
    JAXBContext context = JAXBContext.newInstance(NEFTTransactions.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    // Write to System.out
    m.marshal(bookstore, System.out);

    // Write to File
    m.marshal(bookstore, new File(NEFT_TRANSACTION_XML));

    // get variables from our xml file, created before
    System.out.println();
    System.out.println("Output from our XML File: ");
    Unmarshaller um = context.createUnmarshaller();
    NEFTTransactions bookstore2 = (NEFTTransactions) um.unmarshal(new FileReader(NEFT_TRANSACTION_XML));
    ArrayList<TransactionBean> list = bookstore2.getBooksList();
    for (TransactionBean transaction : list) {
        System.out.println("Transaction Id: " + transaction.getTransId());
        System.out.println("From A/c: " + transaction.getFromAccountNo());
        System.out.println("From IFSC: " + transaction.getFromIFSC());
        System.out.println("To A/c: " + transaction.getToAccountNo());
        System.out.println("To IFSC: " + transaction.getToIFSC());
        System.out.println("Amount: " + transaction.getAmount());
        System.out.println("Date: " + transaction.getDate());
        System.out.println("Time: " + transaction.getTime());
        System.out.println("Description: " + transaction.getDescription());
      }
  }
} 